<template>
  <el-row > 
    <el-col :span="14" class="col-container">
      用户名：<el-input v-model="selectUsername" placeholder="请输入用户名" style="width: 200px;margin-right: 10px;" />
      <el-button type="primary" @click="selectInfosByWhere"><el-icon><Search /></el-icon>查询</el-button>
  </el-col>
  <el-col :span="8" class="col-container">
      <el-button type="primary" @click="openDialog"><el-icon><Plus /></el-icon>添加用户</el-button>
  </el-col>
  <el-col :span="2">
  </el-col>
</el-row>

    <el-table :data="userList"  stripe border>
      <el-table-column prop="name" label="用户名" width="150" />
      <el-table-column prop="pass" label="密码" width="150">
        <template #default="{ row }">
          {{ row.pass.replace(/./g, '*') }}
        </template>
      </el-table-column>
      <el-table-column prop="tel" label="电话" width="150" />
      <el-table-column prop="beizhu" label="备注" />
      <el-table-column label="操作" width="200">
        <template #default="{row}">
          <el-button
            type="primary"
            size="small"
            @click="openModifyDialog(row.id)"
          >
          <el-icon><Edit /></el-icon>编辑
          </el-button>

          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row.id)"
          >
          <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="500px">
      <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
        </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleOp">确认</el-button>
      </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, resolveDirective } from 'vue'
import { ElMessage } from 'element-plus';
import axios from '@/utils/request.js'
// 初始测试数据
const userList = reactive([
])

const form = reactive({
  username: '',
  password: '',
  phone: '',
  remark: '',
  id: ''
})

const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在6到18个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
})

const dialogVisible = ref(false)
const formRef = ref(null)
//查询条件selectUsername = ref('')
const selectUsername=ref('')
const title = ref('新增用户')
//开关
const key=ref(false)

//新增用户
const openDialog = () => {
  key.value=false
  title.value = '新增用户'
  //弹出对话框
  dialogVisible.value= true
  //清空表单
  Object.keys(form).forEach(key => form[key] = '')
}
//打开修改用户信息对话框
const openModifyDialog = (id) => {
  key.value=true
  title.value = '修改用户'
  dialogVisible.value = true
  //清空表单
  Object.keys(form).forEach(key => form[key] = '')
  //根据用户的id加载用户信息
  axios(
            {
              url: '/user',
              method: 'post',
              params: {
                op: 'selectById',
                id: id
              },
            }).then((res) => {
              form.username = res.name
              form.password = res.pass
              form.phone = res.tel
              form.remark = res.beizhu
              form.id = res.id
            })

}

const handleOp = () => {
  if (key.value) {
    //修改用户信息
    handleModify()
  } else {
    //添加用户
    handleAdd()
  }
}
const handleModify = async () => {
  try {
    //表单验证
    await formRef.value.validate()
    //请使用axios实现用户信息的修改
    var p =  {
                op: 'modify',
                name: form.username,
                pass: form.password,
                tel: form.phone,
                beizhu: form.remark,
                id: form.id
              }
    axios(
            {
              url: '/user',
              method: 'post',
              params:p
            }
    ).then((res) => {
      if(res.result=='success'){
                 ElMessage.success('修改成功!');
                  dialogVisible.value = false
                  loadUserData()
              }else {
                ElMessage.error('修改失败，请检查数据是否正确!');
              }
               
     }).catch((error) => {
      ElMessage.error('网络请求失败，请检查网络是否畅通!');
     })
  }catch (e) {
    console.log('表单验证失败')
  }
}
//条件查询
const selectInfosByWhere = async () => {
  //请使用axios实现用户信息的查询
  axios(
            {
              url: '/user',
              method: 'post',
              params: {
                op: 'selectByWhere',
                name: selectUsername.value
              },
            }).then((res) => {
               userList.splice(0, userList.length, ...res)
            })
}
//添加用户
const handleAdd = async () => {
  try {
    //表单验证
    await formRef.value.validate()
    //请使用axios实现用户信息的提交
    axios(
            {
              url: '/user',
              method: 'post',
              params: {
                op: 'add',
                name: form.username,
                pass: form.password,
                tel: form.phone,
                beizhu: form.remark
              },
            }).then((res) => {
              if(res.result=='success'){
                 ElMessage.success('保存成功!');
                  dialogVisible.value = false
                  loadUserData()
              }else {
                ElMessage.error('保存失败，请检查数据是否正确!');
              }
            
               
            }).catch((error) => {
               ElMessage.error('网络请求失败，请检查网络是否畅通!');
            })
    
  } catch (e) {
    console.log('表单验证失败')
  }
}

const handleDelete = (id) => {
  //请使用axios实现用户信息的删除
  axios(
            {
              url: '/user',
              method: 'post',
              params: {
                op: 'delete',
                id: id
              },
            }).then((res) => {
              if(res.result=='success'){
                 ElMessage.success('删除成功!');
                  loadUserData()
              }else {
                ElMessage.error('删除失败，请检查数据是否正确!');
              }
            })

}
//写一个方法，使用axios加载用户数据，将数据放在userList中
const loadUserData = async () => {
  axios(
            {
              url: '/user',
              method: 'post',
              params: {
                op: 'selectAll'
              },
            }).then((res) => {
               userList.splice(0, userList.length, ...res)
               
            }).catch((error) => {
                 ElMessage.error('网络请求失败，请检查网络是否畅通!');
                //  ElMessage.warning('请检查服务器是否开启!');
                //  ElMessage.success('请检查数据库是否连接!');
            });
}
//vue的生命周期方法，当页面加载完成时执行
onMounted(()=>{
  loadUserData()
})


</script>

<style>
  .el-row {
    margin-top: 0rem;
    height: 60px;
    padding: 0cm;
    margin-bottom: 0
  }
  .col-container {
  display: flex;
  align-items: center;  /* 垂直居中 */
  justify-content: flex-end; /* 水平靠右 */
  height: 60px;
  padding: 0px; /* 添加内边距 */
}

</style>